package cn.sxgan.gen.controller;

import cn.sxgan.gen.enums.DataSourceType;
import cn.sxgan.gen.exception.ApiException;
import cn.sxgan.gen.model.ColumnInfo;
import cn.sxgan.gen.model.DbTable;
import cn.sxgan.gen.model.GlobalDataSource;
import cn.sxgan.gen.services.base.DataSourceQuery;
import cn.sxgan.gen.services.base.DataSourceQueryFactory;
import cn.sxgan.gen.services.base.DataSourceService;
import cn.sxgan.gen.services.core.CodeGeneratorService;
import cn.sxgan.gen.utils.Result;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLException;
import java.util.List;

/**
 * @Description: 生成控制器
 * @Author: sxgan
 * @Date: 2025-07-17 17:42
 * @Version: 1.0
 **/
@Slf4j
@Controller
@RequestMapping("/generate")
public class GenerateController {
    
    @Autowired
    private CodeGeneratorService codeGenerator;
    
    @Autowired
    private DataSourceService dataSourceService;
    
    
    @Autowired
    DataSourceQueryFactory dataSourceQueryFactory;
    
    
    @ResponseBody
    @GetMapping("/{tableName}")
    public String generateCode(@PathVariable String tableName) throws Exception {
        codeGenerator.generate(tableName);
        return "代码生成成功!";
    }
    
    
    // 主页显示
    @GetMapping("/main")
    public String index(Model model, HttpServletRequest request) {
        // 获取所有数据源
        List<GlobalDataSource> dataSources = dataSourceService.getAllDataSources();
        // 获取当前激活的数据源
        GlobalDataSource activeDataSource = dataSourceService.getActiveDataSource();
        // 获取当前数据源的所有表
        DataSourceType dataSourceType = DataSourceType.getEnumValue(activeDataSource.getDbType());
        if (dataSourceType == null) {
            throw new ApiException("未知的数据库类型");
        }
        DataSourceQuery dataSourceQuery = dataSourceQueryFactory.getDataSourceQuery(dataSourceType);
        List<DbTable> dbTables = dataSourceQuery.selectDbTables(null);
        String baseUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
        model.addAttribute("baseUrl", baseUrl);
        model.addAttribute("dataSources", dataSources);
        model.addAttribute("activeDataSource", activeDataSource);
        // model.addAttribute("tables", dbTables);
        return "index";
    }
    
    @GetMapping("/datasource")
    @ResponseBody
    public Result<List<GlobalDataSource>> getDatasource() throws SQLException {
        // 获取所有数据源
        List<GlobalDataSource> dataSources = dataSourceService.getAllDataSources();
        return Result.success(dataSources, dataSources.size());
    }
    
    @GetMapping("/tables")
    @ResponseBody
    public List<DbTable> getTables() throws SQLException {
        GlobalDataSource activeDataSource = dataSourceService.getActiveDataSource();
        DataSourceType dataSourceTypeEnum = DataSourceType.getEnumValue(activeDataSource.getDbType());
        if (dataSourceTypeEnum == null) {
            throw new ApiException("不支持的数据库类型");
        }
        DataSourceQuery dataSourceQuery = dataSourceQueryFactory.getDataSourceQuery(dataSourceTypeEnum);
        List<ColumnInfo> sysUser = dataSourceQuery.getTableColumns("sys_user");
        sysUser.forEach(item -> log.info(item.toString()));
        List<DbTable> dbTables = dataSourceQuery.selectDbTables(null);
        // dbTables.forEach(item -> log.info(item.toString()));
        return dbTables;
    }
    
    // // 添加数据源
    // @PostMapping("/datasource/add")
    // public ResponseEntity<?> addDataSource(@RequestBody DataSourceDTO dsDto) {
    //     dataSourceService.addDataSource(dsDto);
    //     return ResponseEntity.ok().build();
    // }
    //
    // // 激活数据源
    // @PostMapping("/datasource/activate")
    // public ResponseEntity<?> activateDataSource(@RequestBody Map<String, String> req) {
    //     dataSourceService.activateDataSource(req.get("id"));
    //     return ResponseEntity.ok().build();
    // }
    //
    // // 生成代码
    // @PostMapping("/generate")
    // public ResponseEntity<Resource> generateCode(@RequestBody CodeGenRequest request) {
    //     // 生成代码逻辑
    //     byte[] zipBytes = codeGenerator.generateCode(
    //             request.getTables(),
    //             request.getPackageName(),
    //             request.getOptions()
    //     );
    //
    //     ByteArrayResource resource = new ByteArrayResource(zipBytes);
    //     return ResponseEntity.ok()
    //             .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=generated-code.zip")
    //             .contentType(MediaType.APPLICATION_OCTET_STREAM)
    //             .contentLength(zipBytes.length)
    //             .body(resource);
    // }
}